const api = require("../pages/user/api.js");
const network = require('./network.js');
const {auth} = require("./auth.js");

let code = '';
const fn = function (res) {
  console.log(res, 'res=================================');
  network.post(api.login, {
    Code: code,
    Platform: 'smallProgram',
    Iv: res.iv,
    EncryptedData: res.encryptedData
  }).then(data => {
    console.log(data, '登录接口成功');
    const withParams = wx.getStorageSync('withParams');
    dealUserInfo(data);
    let userMessage = {};
    if (wx.getStorageSync('user')) {
      userMessage = JSON.parse(wx.getStorageSync('user'));
    }
    if (withParams) {
      // 客户扫码进来
      const url = wx.getStorageSync('parnerUrl');
      network.post(api.ScanningQRCode, {
        IsNewUser: userMessage.IsNewUser,
        PageUrl:  url,
        ScanningIdentity: 'consumer' // ['promoters' => 促销员, 'merchants' => 商家, 'consumer' =》 客户]
      }).then((data) => {
        let success = false;
        let title = '';
        const result = data.QRCodeReturnString.toLocaleLowerCase();
        switch(result) {
          case 'qrcodeerror':
            title = '不支持的二维码';
            break;
          case 'alreadybound':
            title = '绑定失败，已绑定过';
            break;
          case 'bindsuccess':
            title = '绑定成功';
            success = true;
            break;
        }
        wx.removeStorageSync('parnerUrl');
        wx.removeStorageSync('withParams');
        setTimeout(() => {wx.redirectTo({url: '/pages/home/main/index'});}, 3000);
        if (success) {
          wx.navigateToMiniProgram({
            appId: data.AppId,
            path: `/pages/home/main/index?u=${data.UserPkId}`
          });
        }
        console.log(data, "客户");
      }, (e) => {
        setTimeout(() => {wx.redirectTo({url: '/pages/home/main/index'});}, 3000);
        console.log(e, 'error');
        wx.showToast({
          title: 'err',
          icon: 'none'
        });
      })
    } else {
      wx.removeStorageSync('parnerUrl');
      wx.removeStorageSync('withParams');
      wx.redirectTo({url: '/pages/home/main/index'});
    }
    console.log(withParams, 'withParams ========================');
    // wx.redirectTo({url: '/pages/home/main/index'});
  }, () => {
    console.log('登录接口失败');
  });
}

/**
 * 登录
 */
const login = (dealFn) => {
  console.log('开始调用登录接口');
  wx.login({
    success: res => {
      console.log(res, 8888);
      if (res.code) {
        code = res.code;
        auth.userInfo(fn, dealFn);
      }
    },
    fail: err => {
      console.log(err, 777);
    }
  })
}
/**
 * 自动登录
 * @param fn
 */
/*
const isLogin = (fn) => {
  console.log('开始调用自动登录接口');
  network.get(api.isLogin).then(data => {
    console.log(data, '自动登录成功');
    wx.redirectTo({url: '/pages/home/main/index'});
    try {
      wx.setStorageSync('user', JSON.stringify(data))
    } catch (e) {
    }
    // fnComplete();
    // cb();
  }, (err) => {
    // 自动登录失败
    console.log(err, '自动登录失败');
    fn();
  });
}
*/
const isLogin = (dealFn) => {
  console.log('开始调用自动登录接口');
  network.get(api.isLogin).then(data => {
    console.log('自动登录成功');
    wx.removeStorageSync('parnerUrl');
    wx.removeStorageSync('withParams');
    try {
      wx.setStorageSync('user', JSON.stringify(data))
    } catch (e) {
    }
    dealFn(data, 'isLogin');
  }, (err) => {
    // 自动登录失败
    console.log(err, '自动登录失败');
    dealFn(err, 'isLoginFail');
  });
}
/**
 * 处理获取的用户信息
 */
const dealUserInfo = (data) => {
  try {
    wx.setStorageSync('user', JSON.stringify(data))
  } catch (e) {
  }
  try {
    wx.setStorageSync('token', data.Token)
  } catch (e) {
  }
}

exports.login = login;
exports.isLogin = isLogin;